package com.share.user.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.exception.ServiceException;
import com.share.user.api.domain.UpdateUserLogin;
import com.share.user.api.domain.UserCountVo;
import com.share.user.api.domain.UserInfo;
import com.share.user.api.domain.UserLoginLog;
import com.share.user.mapper.UserLoginLogMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.service.IUserInfoService;
import org.springframework.util.ObjectUtils;

/**
 * 用户Service业务层处理
 *
 * @author atguigu
 * @date 2025-10-17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    private final UserInfoMapper userInfoMapper;
    private final WxMaService wxMaService;
    private final UserLoginLogMapper userLoginLogMapper;

    /**
     * 查询用户列表
     *
     * @param userInfo 用户
     * @return 用户
     */
    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        return userInfoMapper.selectUserInfoList(userInfo);
    }

    /**
     * 小程序授权登录
     *
     * @param code
     * @return
     */
    @Override
    public UserInfo wxLogin(String code) {
        //1.通过code，appid，secret获取微信小程序的唯一凭证openid
        String openId;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
            log.info("【小程序授权】openId={}", openId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("微信登录失败");
        }

        //2.通过openId去数据库中查询用户，如果有则返回，如果没有则创建用户、
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if (ObjectUtils.isEmpty(userInfo)) {
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openId);
            userInfo.setAvatarUrl("http://159.75.124.60:9000/spzx/b_0deb4e7fb9959b1f728617cd63c536a7.jpg");
            userInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            userInfo.setCreateTime(new Date());
            userInfo.setUpdateTime(new Date());
            userInfoMapper.insert(userInfo);
        }
        return userInfo;
    }

    /**
     * 更新用户登录信息
     *
     * @param updateUserLogin
     * @return
     */
    @Override
    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getUserId());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfoMapper.updateById(userInfo);

        //登录日志
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(updateUserLogin.getUserId());
        userLoginLog.setMsg("小程序登录");
        userLoginLog.setIpaddr(updateUserLogin.getLastLoginIp());
        userLoginLogMapper.insert(userLoginLog);
        return null;
    }

    /**
     * 判断是否免押金
     *
     * @return
     */
    @Override
    public Boolean isFreeDeposit() {
        //1.通过当前登录的微信用户的id获取当前用户信息
        Long userId = SecurityContextHolder.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //2.修改用户的押金状态
        userInfo.setDepositStatus("1");
        userInfo.setUpdateTime(new Date());
        userInfoMapper.updateById(userInfo);
        return true;
    }

    /**
     * 统计用户注册数据
     *
     * @return
     */
    @Override
    public Map<String, Object> getUserCount() {
        List<UserCountVo> list = userInfoMapper.selectUserCount();

        Map<String, Object> map = new HashMap<>();
        //创建两个list集合，一个对应所有的日期，另一个对应所有数据
        //获取所有日期
        List<String> dateList = list.stream().map(UserCountVo::getRegisterDate).collect(Collectors.toList());
        //获取所有数据
        List<Integer> countList = list.stream().map(UserCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }
}
